import { useAuth } from "context/auth-context";
import { Form, Input } from "antd";
import { LongButton } from "unauthenticated-app";
import { useAsync } from "util/use-async";

export const RegisterScreen = ({
  onError,
}: {
  onError: (error: Error) => void;
}) => {
  const { register } = useAuth();

  const { run, isLoading } = useAsync(undefined, { throwOnError: true });

  const handleSumbit = async (value: {
    username: string;
    password: string;
    cpassword: string;
  }) => {
    const { password, cpassword } = value;
    try {
      if (cpassword !== password) {
        throw new Error("確認密碼不正確");
      }
      await run(register(value));
    } catch (e) {
      onError(e);
    }
  };

  return (
    <Form onFinish={handleSumbit}>
      <Form.Item
        name="username"
        rules={[{ required: true, message: "請輸入用戶名" }]}
      >
        <Input placeholder={"用戶名"} type="text" id={"username"} />
      </Form.Item>
      <Form.Item
        name="password"
        rules={[{ required: true, message: "請輸入密碼" }]}
      >
        <Input placeholder={"密碼"} type="password" id={"password"} />
      </Form.Item>
      <Form.Item
        name="cpassword"
        rules={[{ required: true, message: "請確認密碼" }]}
      >
        <Input placeholder={"確認密碼"} type="password" id={"cpassword"} />
      </Form.Item>
      <Form.Item>
        <LongButton loading={isLoading} htmlType={"submit"} type={"primary"}>
          注冊
        </LongButton>
      </Form.Item>
    </Form>
  );
};
